package logic

import (
	"context"
	"encoding/json"
	"github.com/go-redis/redis/v7"
	"github.com/olivere/elastic/v7"
	"github.com/zeromicro/go-zero/core/logx"
	"log"
	"month/models"
	"month/rpc/internal/svc"
	"month/rpc/month"
)

type EsSelLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewEsSelLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EsSelLogic {
	return &EsSelLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// es查询
func (l *EsSelLogic) EsSel(in *month.EsSelRequest) (*month.EsResponse, error) {
	// todo: add your logic here and delete this line

	//接收关键词
	name := in.Name

	//初始化es连接
	esClient, err := elastic.NewClient(elastic.SetURL("http://43.143.123.142:9200"), elastic.SetSniff(false))
	if err != nil {
		return &month.EsResponse{
			Code:    400,
			Message: "elastic连接失败",
		}, err
	}
	var data []models.Fgit

	//分词搜索
	anaRes, err := elastic.NewIndicesAnalyzeService(esClient).Analyzer("ik_smart").Text(name).Do(context.Background())
	for _, v := range anaRes.Tokens {

		//根据分词结果再次高亮查询
		hl := elastic.NewHighlight().Field("Name").PreTags("<a style='color: red'>").PostTags("<a>")
		query := elastic.NewMatchQuery("Name", v.Token)

		res, err := esClient.Search().Index("fgit").Query(query).Highlight(hl).Do(context.Background())
		if err != nil {
			return &month.EsResponse{
				Code:    400,
				Message: "es查询失败",
			}, nil
		}

		for _, vv := range res.Hits.Hits {
			var fs models.Fgit
			err := json.Unmarshal(vv.Source, &fs)
			if err != nil {
				return &month.EsResponse{
					Code:    400,
					Message: "json解析失败",
				}, nil
			}
			data = append(data, fs)
		}
	}

	//将数据存入redis排行榜
	redisClient := redis.NewClient(&redis.Options{
		Addr:     "http://43.143.123.142:6379",
		DB:       1,
		Password: "",
	})
	for _, v := range data {
		redisClient.ZAdd("fgit", &redis.Z{Member: v, Score: float64(v.Lz)})
	}

	//查询排行榜
	red := redisClient.ZRangeWithScores("fgit", 0, 9)
	for _, v := range red.Val() {
		log.Println(v)
	}

	//数据打包
	ed, _ := json.Marshal(data)

	return &month.EsResponse{
		Code:    200,
		Message: "成功",
		Data:    string(ed),
	}, nil
}
